package com.updesignsz.admin.controller;

import com.updesignsz.admin.service.UserService;
import com.updesignsz.admin.util.ResponseUtil;
import com.updesignsz.admin.vo.form.UserLoginForm;
import com.updesignsz.commom.entity.User;
import com.updesignsz.commom.util.EncryptUtil;
import com.updesignsz.commom.util.ResultVo;
import com.updesignsz.commom.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * TODO
 * Created User: lx
 * Date: 2020/4/26 17:34
 */
@RestController
@RequestMapping(value = "/system")
public class LognController {

    @Autowired
    private UserService userService;


    @PostMapping(value = "/login")
    public void login(@Validated @RequestBody UserLoginForm userForm, HttpServletResponse response) {

        ResultVo vo = new ResultVo();
        try {
            User user = userService.login(userForm.getUsername(), StringUtil.toMD5(userForm.getPassword()));
            if (user != null) {
                Map<String, Object> map = new HashMap<>();
                map.put("token", EncryptUtil.getInstance().AESencode(user.getId().toString()));
                map.put("modules", userService.getUserRoleModule(user.getId()));
                map.put("functions", userService.getUserRoleFunction(user.getId()));
                vo.setData(map);
            } else {
                vo.setResultVo(1, "登录失败,帐号或密码错误!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        ResponseUtil.outJson(vo.toJsonMsg(), response);
    }


    @RequestMapping(value = "/get_info")
    public void get_info(String token, HttpServletResponse response) {
        ResultVo vo = new ResultVo();
        try {
            System.out.println("token--->:" + token);
            String userId = EncryptUtil.getInstance().AESdecode(token);
            if (StringUtil.isNotEmpty(userId)) {
                Map<String, Object> map = new HashMap<>();
                map.put("token", EncryptUtil.getInstance().AESencode(userId));
                map.put("modules", userService.getUserRoleModule(StringUtil.toInt(userId)));
                map.put("functions", userService.getUserRoleFunction(StringUtil.toInt(userId)));
                vo.setData(map);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        ResponseUtil.outJson(vo.toJsonMsg(), response);
    }
}
